package org.apache.ofbiz.services;

import com.ruoyi.doc.domain.Company;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.constant.ConstKit;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.condition.EntityCondition;
import org.apache.ofbiz.entity.condition.EntityOperator;
import org.apache.ofbiz.entity.model.DynamicViewEntity;
import org.apache.ofbiz.entity.model.ModelKeyMap;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 北京XXX信息技术有限公司-版权所有
 *
 * @author yuanpingfang
 * @version 1.0
 * @Package org.apache.ofbiz.services
 * @ClassName CompanyServices
 * @Description 公司内容服务
 * @date 2021-4-20 14:34
 */
public class CompanyServices {

    public static final String module = CompanyServices.class.getName();

    /**
     * @param
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Title selectCompanyById
     * @Description 查询公司内容
     * @author yuanpingfang
     * @date 2021-4-20 14:34
     */
    public static Map<String, Object> selectCompanyById(DispatchContext dctx, Map<String, Object> context) {
        Delegator delegator = dctx.getDelegator();
        //Locale locale = (Locale) context.get("locale");
        String CompanyId = (String) context.get("companyId");
        GenericValue CompanyValue = null;
        try {
            CompanyValue = EntityQuery.use(delegator).from("Content").where("CompanyId", CompanyId).queryFirst();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
        Map<String, Object> returnMap = ServiceUtil.returnSuccess();
        returnMap.put("company", CompanyValue);
        return returnMap;
    }

    /**
     * @param
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Title selectCompanyList
     * @Description 查询公司内容列表
     * @author yuanpingfang
     * @date 2021-4-20 10:13
     */
    public static Map<String, Object> selectCompanyList(DispatchContext dctx, Map<String, Object> context) {
        LocalDispatcher dispatcher = dctx.getDispatcher();
        Company company = (Company) context.get("company");
        Integer pageNum = (Integer) context.get("pageNum");
        Integer pageSize = (Integer) context.get("pageSize");
        String orderBy = (String) context.get("orderBy");

        if (UtilValidate.isEmpty(orderBy)) {
            orderBy = "-lastUpdatedStamp";
        }
        List<EntityCondition> conditions = new ArrayList<>();
        DynamicViewEntity dve = null;
        String entityName = "Content";

        // 后期考虑使用es进行检索
        if (UtilValidate.isNotEmpty(company.getContentName())) {
            conditions.add(EntityCondition.makeCondition("contentName", EntityOperator.LIKE, "%" + company.getContentName() + "%"));
        }

        if (UtilValidate.isNotEmpty(company.getPartyId())) {
            dve = new DynamicViewEntity();
            dve.addMemberEntity("PC", "PartyContent");
            dve.addAlias("PC", "partyId");
            dve.addAlias("PC", "contentId");
            dve.addMemberEntity("CO", "Content");
            dve.addAliasAll("CO", "", null); // no prefix
            dve.addAlias("CO", "lastUpdatedStamp");
            dve.addViewLink("PC", "CO", Boolean.TRUE, ModelKeyMap.makeKeyMapList("contentId", "contentId"));
            conditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, company.getPartyId()));
            entityName = null;
        } else {
            String folderId = company.getFolderId();
            if (UtilValidate.isNotEmpty(folderId)) { // 代表是根据文件夹查下级
                dve = new DynamicViewEntity();
                dve.addMemberEntity("CA", "ContentAssoc");
                dve.addAlias("CA", "assocContentId", "contentId", null, null, null, null);
                dve.addAlias("CA", "contentIdTo");
                dve.addAlias("CA", "contentAssocTypeId");
                dve.addMemberEntity("CO", "Content");
                dve.addAliasAll("CO", "", null); // no prefix
                dve.addAlias("CO", "lastUpdatedStamp");
                dve.addAlias("CO", "contentId");
                dve.addViewLink("CA", "CO", Boolean.TRUE, ModelKeyMap.makeKeyMapList("contentIdTo", "contentId"));
                conditions.clear();
                conditions.add(EntityCondition.makeCondition("assocContentId", EntityOperator.EQUALS, folderId));
                conditions.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, ConstKit.CONTENT_ASSOC_TYPE_SUB));
                entityName = null;
            }
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("entityName", entityName);
        queryMap.put("dve", dve);
        queryMap.put("pageNum", pageNum);
        queryMap.put("pageSize", pageSize);
        queryMap.put("queryCondition", EntityCondition.makeCondition(conditions));
        queryMap.put("orderBy", orderBy);// 多个排序字段 "|" 符连接
        queryMap.put("fields", "");// 多个查询字段 "|" 符连接
        //queryMap.put("distinct","Y");
        Map<String, Object> queryPageMap = null;
        try {
            queryPageMap = dispatcher.runSync("queryPageList", queryMap);
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
        return queryPageMap;
    }

    /**
     * @param
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @Title deleteCompanyByIds
     * @Description 批量删除公司内容服务
     * @author yuanpingfang
     * @date 2021-4-20 13:08
     */
    public static Map<String, Object> deleteCompanyByIds(DispatchContext dctx, Map<String, Object> context) {
        Delegator delegator = dctx.getDelegator();
        List CompanyIds = UtilGenerics.checkList(context.get("companyIds"));
        try {
            delegator.removeByCondition("Company", EntityCondition.makeCondition("CompanyId", EntityOperator.IN, CompanyIds));
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
        return ServiceUtil.returnSuccess();
    }

    public static Map<String, Object> selectPartyContent(DispatchContext dctx, Map<String, Object> context) {
        Delegator delegator = dctx.getDelegator();
        String parentNodeId = (String) context.get("parentNodeId");
        String partyContentTypeId = (String) context.get("partyContentTypeId");
        List<EntityCondition> conditions = new ArrayList<>();
        DynamicViewEntity dve = new DynamicViewEntity();
        // 需要判断是移动到机构还是文件夹下面了
        List<GenericValue> contentValues = null;
        try {
            Long count = EntityQuery.use(delegator).from("Content").where("contentId", parentNodeId).cache().queryCount();
            if (count > 0) {//是文件夹
                dve.addMemberEntity("CA", "ContentAssoc");
                dve.addAlias("CA", "assocContentId", "contentId", null, null, null, null);
                dve.addAlias("CA", "contentIdTo");
                dve.addAlias("CA", "contentAssocTypeId");
                dve.addViewLink("CA", "CO", Boolean.TRUE, ModelKeyMap.makeKeyMapList("contentIdTo", "contentId"));
                conditions.add(EntityCondition.makeCondition("assocContentId", EntityOperator.EQUALS, parentNodeId));
                conditions.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, ConstKit.CONTENT_ASSOC_TYPE_SUB));
            } else {
                dve.addMemberEntity("PC", "PartyContent");
                dve.addAlias("PC", "partyId");
                dve.addAlias("PC", "contentId");
                dve.addAlias("PC", "partyContentTypeId");
                dve.addViewLink("PC", "CO", Boolean.TRUE, ModelKeyMap.makeKeyMapList("contentId", "contentId"));
                conditions.add(EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, parentNodeId));
                conditions.add(EntityCondition.makeCondition("partyContentTypeId", EntityOperator.EQUALS, partyContentTypeId));
            }
            dve.addMemberEntity("CO", "Content");
            dve.addAliasAll("CO", "", null); // no prefix
            contentValues = EntityQuery.use(delegator).from(dve).where(conditions).queryList();
        } catch (GenericEntityException e) {
            Debug.log(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
        Map<String, Object> returnMap = ServiceUtil.returnSuccess();
        returnMap.put("contentList", contentValues);
        return returnMap;
    }

}
